import { StoreHelper } from "../../utils/storeHelper";
import { CreepHelper } from "../../utils/creepHelper";

/**
 * 专门为upgrade搬运资源的creep，解决upgrade来回跑的问题
 */
class UpgradeCarryTask implements ICreepTask {
  public run(creep: Creep): void {

    if(!creep.memory.transferBlacklist){
      creep.memory.transferBlacklist = new Array<string>();
    }

    if(creep.memory.working){
      // 找到最近的未满能量存储设施
      let target:StructureContainer | undefined = undefined;

      if(!creep.memory.transferTarget){
        target = StoreHelper.findClosestControllerNotFullContainer(creep.room);
        if(target){
          creep.memory.transferTarget = target.id;
        }
      }
      else {
        let obj = Game.getObjectById(creep.memory.transferTarget) as StructureContainer;
        if(obj){
          target = obj;
        }
        else{
          delete creep.memory.transferTarget;
        }
      }

      if (target) {
        // 如果有未满能量存储设施，就将能量转移到它
        let result = creep.transfer(target, RESOURCE_ENERGY);
        if(result == OK){
          // 如果储存成功把 对应的ID放进黑名单，防止再从里面拿出来
          if(creep.memory.transferBlacklist.indexOf(target.id) === -1){
            creep.memory.transferBlacklist.push(target.id);
          }
        }
        if (result === ERR_NOT_IN_RANGE) {
          creep.go(target.pos);
        }
        if(result === ERR_NOT_ENOUGH_RESOURCES){
          creep.memory.working = false;
        }
      }
    }else {
      //如果拾取未满最大容量则继续拾取
      CreepHelper.creepPickup(creep, creep.memory.transferBlacklist);
    }
    
  }
}

export { UpgradeCarryTask };